<template>
  <div>
    <publink-select
      class="user-search"
      :value="value"
      value-key="id"
      filterable
      remote
      clearable
      is-search-user
      :placeholder="placeholder"
      :multiple="multiple"
      :remote-method="keywordSearch"
      v-el-select-loadmore="loadMoreOptions"
      @input="updateSelectValue"
      @focus="focus"
    >
      <el-option
        v-for="(item, index) in options"
        :key="index + '_' + item.id"
        :label="item.name"
        :origin="item"
        :value="item"
      >
        <template v-if="isOpenData">
          <open-data type="userName" :openid="item.staffId" :name="item.name"></open-data>
          <template v-if="item.isDelete == 1">{{ ` (${t('common.base.resigned')})` }}</template>
        </template>
      </el-option>
      <!-- <template slot="multiple" slot-scope="{ item }">
        <template v-if="isOpenData">
          <open-data type="userName" :openid="item.staffId"></open-data>
        </template>
        <template v-else>
          {{ item.currentLabel }}
        </template>
      </template> -->
    </publink-select>
  </div>
</template>

<script>
import { defineComponent, ref, computed } from 'vue';
import i18n from '@src/locales';
import { debounce } from 'lodash';
import { isOpenData } from '@src/util/platform';

export default defineComponent({
  name: 'UserSearch',
  props: {
    field: {
      type: Object,
      default: null,
    },
    placeholder: {
      type: String,
      default: i18n.t('common.placeholder.selectUser'),
    },
    remoteMethod: {
      type: Function,
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    isConnector: {
      type: Boolean,
      default: false,
    },
    value: {
      type: [Array, Object],
      default: () => [],
    },
  },
  emits: ['update'],
  setup(props, { emit }) {
    const selectValue = computed(() =>
      Array.isArray(props.value) ? props.value : props.value
    );
    const options = ref(
      props.value
        ? Array.isArray(props.value)
          ? [...props.value]
          : [props.value]
        : []
    ); // 默认 回显选项使用options
    const searchParam = ref({
      pageNum: 1,
      keyword: '',
    });
    const hasNextPage = ref(true);

    const loading = ref(false);

    const emptyOoption = () => ({
      id: 'empty',
      name: i18n.t('customer.empty'),
      staffId: ''
    })
    // 搜索
    const search = async function search() {
      const defaultOptions = props.field.emptySearch ? [emptyOoption()] : []
      try {
        if (loading.value) return;
        if (!props.remoteMethod) return console.warn('请提供用户查询方法');
        loading.value = true;
        const res = await props.remoteMethod(searchParam.value);
        if (!res || !res.list) return (options.value = defaultOptions);

        if (searchParam.value.pageNum === 1) {
          options.value = defaultOptions;
        }

        hasNextPage.value = !res.isLastPage;
        loadMoreOptions.value.disabled = !hasNextPage.value;
        options.value.push(...res.list);
      } catch (error) {
        options.value = defaultOptions;
      } finally {
        loading.value = false;
      }
    };

    // 关键字搜索
    function keywordSearch(keyword) {
      searchParam.value.keyword = keyword.trim();
      searchParam.value.pageNum = 1;
      search();
    }

    // 聚焦输入框第一次 默认搜索一下
    function focus() {
      // 连接器人员搜索的时候默认搜索
      // if (options.value.length && !props.isConnector) return;
      if (!props.multiple) {
        emit('update', {});
      }
      keywordSearch('');
    }

    // 加载更多
    const loadMore = debounce(() => {
      if (!hasNextPage.value || loading.value) return;
      searchParam.value.pageNum++;
      search();
    });

    // 选中更新值
    function updateSelectValue(value) {
      // const newValue = value.map(item => {
      //   return item;
      // });
      emit('update', value);
    }

    const loadMoreOptions = computed(() => ({
      disabled: loading.value,
      callback: loadMore,
      distance: 10,
    }));

    return {
      selectValue,
      options,
      loadMoreOptions,
      focus,
      keywordSearch,
      updateSelectValue,
    };
  },
  data() {
    return {
      isOpenData
    };
  }
});
</script>

<style lang="scss">
.user-search {
  width: 100%;
  .el-tag .open-data {
    margin-right: 0;
  }
}
</style>
